<?php

class DBC {
/*
    private $conn;
    private $servname = "103.45.101.157,7758";
    private $database = "IIAccount";
    private $uid = "cntw_sql";
    private $pwd = "D@DWx*sHBMSwCF*";
*/
    /*  正式服务器地址、账号、密码   */
    private $servname = "101.35.116.119,7758";
    //private $servname = "117.50.72.98,1433";
    private $database = "TAccount";
    private $uid = "GloryC_sql2017_srv";
    private $pwd = "GLgame_2017!#$%2008";
//    private $uid = "GL_LogUser";
 //   private $pwd = "gg293865ee!@#";
    

    public function __construct($database = "") {
        if ($database == "") {
            $conninfo = array("Database" => $this->database, "UID" => $this->uid, "PWD" => $this->pwd);
        } else {
            $conninfo = array("Database" => $database, "UID" => $this->uid, "PWD" => $this->pwd);
        }
        $this->conn = sqlsrv_connect($this->servname, $conninfo);
        if($this->conn === false){
            die(print_r(sqlsrv_errors(), true));
        }
    }

    /**
     * 查询
     * @param type $sql
     * @return array
     */
    public function fetchData($sql) {
        $array = array();
        $stmt = sqlsrv_query($this->conn, $sql);
        if ($stmt === false) {
            return $stmt;
        }
        while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
            array_push($array, $row);
        }
        sqlsrv_free_stmt($stmt);
        return $array;
    }

    /**
     * 增删改
     * @param type $sql
     * @return type
     */
    public function execute($sql) {
        $stmt = sqlsrv_query($this->conn, $sql);
        if ($stmt === false) {
            return $stmt;
        }
        $rows_affected = sqlsrv_rows_affected($stmt);
        sqlsrv_free_stmt($stmt);
        return $rows_affected;
    }

    /**
     * 批量执行增删改
     * @param array $sqls
     * @return boolean
     */
    public function executeBatch(array $sqls) {
        if (sqlsrv_begin_transaction($this->conn) === false) {
            return false;
        }
        $result = true;
        $sql_size = count($sqls);
        for ($i = 0; $i < $sql_size; $i++) {
            $sql = $sqls[$i];
            $stmt = sqlsrv_query($this->conn, $sql);
            if ($stmt === false) {
                $result = false;
                break;
            }
            sqlsrv_free_stmt($stmt);
        }
        if ($result) {
            sqlsrv_commit($this->conn);
        } else {
            sqlsrv_rollback($this->conn);
        }

        return $result;
    }

    /**
     * 关闭连接
     */
    public function close() {
        if ($this->conn) {
            sqlsrv_close($this->conn);
        }
    }

}

?>
